<template>
  <!-- 菜单管理 -->
  <div class="menuManage">
    <div class="leftContent">
      <div class="treeTit">
        菜单列表
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          class="addTopMenu"
          @click="handleAddTopMenu"
          >新增一级菜单</a-button
        >
      </div>
      <div class="treeContent">
        <a-spin :spinning="loading">
          <a-tree
            v-if="treeData.length"
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            v-model:checkedKeys="checkedKeys"
            default-expand-all
            autoExpandParent
            :tree-data="treeData"
            class="menuManageTree"
          >
            <template #title="{ name, id, parentId, parentName }">
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                "
              >
                <div
                  :class="
                    id === selectedMenu ? 'treeTitle active' : 'treeTitle'
                  "
                  @click="onSelect(id, parentId)"
                >
                  {{ name }}
                </div>
                <div class="editBtn">
                  <PlusCircleOutlined
                    class="addBtn"
                    @click="handleAddMenu(id, name)"
                  />
                  <a-popconfirm
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="handleDelMenu(id)"
                  >
                    <template #title>
                      {{ `是否确定删除【${name}】?` }}
                    </template>
                    <DeleteOutlined class="delBtn" />
                  </a-popconfirm>
                </div>
              </div>
            </template>
          </a-tree>
        </a-spin>
      </div>
    </div>
    <div class="rightContent">
      <div class="treeTit">
        {{ editTitle }}
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          class="saveBtn"
          @click="handleSaveMenu"
          >保存</a-button
        >
      </div>
      <a-spin :spinning="formLoading">
        <a-form
          :model="form"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :rules="rules"
          ref="formRef"
          class="formContent"
        >
          <a-form-item label="菜单名称：" name="name">
            <a-input
              v-model:value="form.name"
              class="formInput"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="上级菜单：" v-if="!isTopMenu">
            <a-input
              v-model:value="form.parentName"
              class="formInput"
              placeholder="请输入"
              disabled
            />
          </a-form-item>
          <a-form-item label="页面链接/地址：" name="path">
            <a-input
              v-model:value="form.path"
              class="formInput"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="菜单唯一标识：" name="permission">
            <a-input
              v-model:value="form.permission"
              class="formInput"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="菜单图标：">
            <a-input
              v-model:value="form.icon"
              class="formInput"
              @click="iconChoseVisible = true"
              placeholder="点击选择图标"
              style="cursor: pointer"
            />
          </a-form-item>
          <a-form-item label="排序：">
            <a-input-number
              v-model:value="form.sortOrder"
              class="formInput"
              placeholder="请输入"
              :controls="true"
            />
          </a-form-item>
          <a-form-item label="是否启用数据权限：">
            <a-radio-group v-model:value="form.dataPermi">
              <a-radio :value="0">否</a-radio>
              <a-radio :value="1">是</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="是否存在按钮权限：">
            <a-radio-group v-model:value="form.btnPermi">
              <a-radio :value="0">否</a-radio>
              <a-radio :value="1">是</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </a-spin>
      <div class="btnContent" v-if="form.btnPermi">
        <div class="tit">新增按钮</div>
        <a-divider style="margin: 15px 0" />
        <a-form
          :model="btnform"
          :label-col="{ style: { width: '100px' } }"
          :rules="btnRules"
          ref="btnFormRef"
          layout="inline"
          class="btnForm"
        >
          <a-form-item label="按钮名称：" name="name">
            <a-input
              v-model:value="btnform.name"
              class="btnInput"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="按钮链接/地址：">
            <a-input
              v-model:value="btnform.path"
              class="btnInput"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="按钮唯一标识：" name="permission">
            <a-input
              v-model:value="btnform.permission"
              class="btnInput"
              placeholder="请输入"
            />
          </a-form-item>
          <a-button
            key="submit"
            type="primary"
            :loading="loading"
            @click="handleSaveBtn"
            >提交按钮配置</a-button
          >
        </a-form>
        <a-table
          :dataSource="form.btnList"
          :columns="columns"
          size="small"
          :scroll="{ x: 'max-content' }"
          @resizeColumn="handleResizeColumn"
          :pagination="false"
          :loading="tableLoading"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'handle'">
              <a-popconfirm
                ok-text="确认"
                cancel-text="取消"
                @confirm="confirmBtnDel(record)"
              >
                <template #title> 是否确定删除该按钮？ </template>
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>

              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </div>
  <!-- 选择图标 -->
  <IconChose
    :iconChoseVisible="iconChoseVisible"
    :defaultIcon="form.icon"
    @update:iconChoseVisible="iconChoseVisible = $event"
    @getChoosedIcon="getChoosedIcon"
  />
  <!-- 编辑按钮 -->
  <EditBtn
    :editBtnVisible="editBtnVisible"
    :rowData="rowData"
    @update:editBtnVisible="editBtnVisible = $event"
    @onSelect="onSelect"
  />
</template>
<script setup>

import EditBtn from "./conpoments/editBtn.vue"
import IconChose from "@/views/conpoments/IconChose.vue"
import { MENU_AUTH } from "../../../../constants/stationConfig"
const $api = inject("$api")
const labelCol = { style: { width: "160px" } }
const wrapperCol = { span: 16 }
const iconChoseVisible = ref(false)
const formLoading = ref(false)
const form = ref({
  name: null,
  parentId: -1,
  parentName: null,
  path: null,
  permission: null,
  icon: null,
  sortOrder: null,
  dataPermi: 0,
  btnPermi: 0,
  menuType: MENU_AUTH.menu,
  btnList: [],
})
const btnFormRef = ref(null)
const btnform = ref({
  name: null,
  path: null,
  permission: null,
  menuType: MENU_AUTH.button,
})
const rules = ref({
  name: [
    {
      required: true,
      message: "请输入菜单名称",
      trigger: "blur",
    },
  ],
  permission: [
    {
      required: true,
      message: "请输入菜单唯一标识",
      trigger: "blur",
    },
  ],
})
const btnRules = ref({
  name: [
    {
      required: true,
      message: "请输入按钮名称",
      trigger: "blur",
    },
  ],
  permission: [
    {
      required: true,
      message: "请输入唯一标识",
      trigger: "blur",
    },
  ],
})
const clearForm = () => {
  form.value = {
    name: null,
    parentId: null,
    parentName: null,
    path: null,
    permission: null,
    icon: null,
    sortOrder: null,
    dataPermi: 0,
    btnPermi: 0,
    menuType: MENU_AUTH.menu,
  }
  btnform.value = {
    name: null,
    path: null,
    permission: null,
    menuType: MENU_AUTH.button,
  }
}
const isEdit = ref(false)
const isTopMenu = ref(true)
const selectedMenu = ref("")
const treeData = ref([])
function handleResizeColumn(w, col) {
  col.width = w
}
const loading = ref(false)
const columns = ref([
  {
    title: "按钮名称",
    dataIndex: "name",
    key: "name",
    width: 160,
    resizable: true,
    align: "center",
  },
  {
    title: "链接/地址",
    dataIndex: "path",
    key: "path",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "唯一标识",
    dataIndex: "permission",
    key: "permission",
    width: 160,
    resizable: true,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    width: 100,
    resizable: true,
    align: "center",
    fixed: "right",
  },
])
const rowData = ref({})
const getChoosedIcon = (icon) => {
  form.value.icon = icon
}
const editBtnVisible = ref(false)
const handleEdit = (data) => {
  rowData.value = {
    ...data,
    rowParentId: form.value.parentId,
  }
  editBtnVisible.value = true
}
const editTitle = computed(() => {
  const handleWord = isEdit.value ? "编辑" : "新增"
  const menuWord = isTopMenu.value ? "一级" : "子"
  if (isEdit.value) {
    return `编辑${menuWord}菜单`
  }
  return `${handleWord}${menuWord}菜单`
})
const formRef = ref(null)
const handleSaveMenu = async () => {
  formRef.value
    .validate()
    .then(async () => {
      loading.value = true

      const params = {
        ...form.value,
      }
      if (isEdit.value) {
        params.id = selectedMenu.value
      }
      const res = await $api.baseMenu(params, isEdit.value ? "put" : "post")
      if (res && res.code === 0) {
        console.log("res", res)
        //selectedMenu.value = res.data.id
        message.success(isEdit.value ? "编辑成功" : "新增成功")
        await getBaseMenuList()
        // clearForm();
      }
      loading.value = false
    })
    .catch((error) => {
      console.log("error", error)
    })
}
const handleAddTopMenu = () => {
  clearForm()
  form.value.parentId = -1
  form.value.icon = null
  isEdit.value = false
  isTopMenu.value = true
}
const handleAddMenu = (key, name) => {
  isEdit.value = false
  isTopMenu.value = false
  selectedMenu.value = null
  clearForm()
  form.value.parentId = key
  form.value.parentName = name
}
const onSelect = async (selectedKeys, parentId) => {
  formRef.value.clearValidate()

  if (parentId === -1) {
    isTopMenu.value = true
  } else {
    isTopMenu.value = false
  }
  isEdit.value = true
  selectedMenu.value = selectedKeys
  formLoading.value = true
  const res = await $api.baseMenuDetails(selectedKeys)
  formLoading.value = false
  if (res && res.code === 0) {
    const resData = res.data
    form.value = {
      name: resData.name,
      parentId: resData.parentId,
      parentName: resData.parentName,
      path: resData.path,
      permission: resData.permission,
      icon: resData.icon,
      sortOrder: resData.sortOrder,
      dataPermi: resData.dataPermi,
      btnPermi: resData.btnPermi,
      menuType: MENU_AUTH.menu,
      children: resData.children,
      btnList: resData.btnList,
      dataPermi: resData.dataPermi,
      dataPermissionList: resData.dataPermissionList,
    }
  }
}
const handleDelMenu = async (id) => {
  const res = await $api.baseMenuDel(id, "delete")
  if (res && res.code === 0) {
    message.success("删除成功")
    getBaseMenuList()
  }
}
const getBaseMenuList = async () => {
  loading.value = true
  const res = await $api.baseMenuList({
    menuType: MENU_AUTH.menu,
    all: 1, // 这里需要拉去全量菜单数据
  })
  loading.value = false
  if (res && res.code === 0) {
    treeData.value = res.data
  }
}
const handleSaveBtn = async () => {
  btnFormRef.value
    .validate()
    .then(async () => {
      let newMemuId
      newMemuId = selectedMenu.value
      const params = {
        ...btnform.value,
        parentId: newMemuId,
      }
      if (!params.parentId) {
        message.error("请先保存菜单")
        return
      }
      const res = await $api.baseMenu(params, "post")
      if (res && res.code === 0) {
        message.success("新增按钮成功")
        btnform.value = {
          name: null,
          path: null,
          permission: null,
          menuType: MENU_AUTH.button,
        }
        getBaseMenuList()
        onSelect(newMemuId, form.value.parentId)
      }
    })
    .catch((error) => {
      console.log("error", error)
    })
}
const confirmBtnDel = async (data) => {
  const res = await $api.baseMenuDel(data.id, "delete")
  if (res && res.code === 0) {
    message.success("删除成功")
    getBaseMenuList()
    onSelect(selectedMenu.value, form.value.parentId)
  }
}
onMounted(async () => {
  getBaseMenuList()
})
</script>
<style lang="less">
.menuManageTree {
  font-size: 16px;
  .ant-tree-treenode {
    padding: 0;
    position: initial;
  }
  .ant-tree-node-content-wrapper {
    position: inherit;
  }
}
</style>
<style lang="less" scoped>
.leftContent,
.rightContent {
  display: inline-block;
  height: 100vh;
  box-sizing: border-box;
  background: #141414;
  overflow-y: auto;
}
.leftContent {
  width: 400px;
  margin-right: 20px;
}
.rightContent {
  width: calc(100% - 420px);
}
.treeTit {
  font-size: 18px;
  height: 70px;
  line-height: 70px;
  border-bottom: 1px solid #333;
  position: relative;
  padding: 0 20px;
}
.treeContent {
  width: 100%;
}
.treeContent,
.formContent {
  padding: 20px;
}
.addTopMenu {
  background-color: green;
  color: white;
  vertical-align: middle;
  position: absolute;
  right: 20px;
  top: 19px;
  &:hover {
    background-color: #529b2e;
  }
}
.saveBtn {
  position: absolute;
  right: 20px;
  top: 19px;
}
.editBtn {
  position: absolute;
  right: 0;
}
.addBtn,
.delBtn {
  font-size: 16px;
  margin-left: 10px;
  cursor: pointer;
}
.addBtn {
  color: #1655ad;
}
.delBtn {
  color: red;
}
.ant-input-number {
  width: 100%;
}
.btnForm {
  display: flex;
  justify-content: flex-start;
}
.btnContent {
  padding: 20px;
  .tit {
    font-size: 16px;
  }
  .btnInput {
    // width: 160px;
  }
  .ant-form-item {
    margin-bottom: 20px;
  }
}
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.treeTitle {
  height: 36px;
  line-height: 36px;
}
.active {
  background-color: #1568dc;
  padding: 0 10px;
  border-radius: 4px;
  margin-left: -10px;
}
::v-deep(.ant-tree-switcher-icon) {
  vertical-align: bottom !important;
}
</style>
